package pCloud.server;

import java.net.InetSocketAddress;

import pCloud.PCloudFactory;
import pCloud.config.PCloudConfig;
import pCloud.exception.InvalidConfiguration;
import pCloud.service.AccessControlHandle;
import pCloud.transport.DatabaseAddress;

/**
 * Should be the same as DataServer, except that it does not connect to 
 * database, but owners  
 *
 */
public class CloudServer extends ProxyServer{
	AccessControlHandle accessControlHandler;

	int port; 
	
	public CloudServer(int port, int serverId) {
		super(port, serverId);
		this.port = port;
	
		this.accessControlHandler = null;
	}

	public void init() throws Exception {
		logger = initLog("CloudServer" + serverId,
				PCloudConfig.PCLOUD_DATA_SERVER_LOG);
		this.communicator.init(logger);
		
		this.initAccessControl();

		this.acceptingClientConnections();
	}
	

	private void initAccessControl() throws Exception {
		this.accessControlHandler = PCloudFactory
				.getNewAccessControlHandleInstance(PCloudConfig
						.getString(PCloudConfig.PCLOUD_ACCESS_CONTROL_PROT));
		this.accessControlHandler.init();
	}

	void acceptingClientConnections() throws Exception {
		new CloudServerAcceptor(this.listeningPort, this.communicator,
				 this.accessControlHandler).accept();
	}

	public static void main(String[] args) throws Exception {

		// 2 data servers, run both instances
		String configFile = PCloudConfig.DEFAULT_CONFIG_FILE;

		if (args.length > 0) {
			configFile = args[0];
		}

		PCloudConfig.init(configFile);
		String[] addr = PCloudConfig.getString(
				PCloudConfig.PCLOUD_DATA_SERVER_ADDRESS).split(" ");

		int nServers = new Integer(addr[0]).intValue();
		if (nServers != 1)
			throw new InvalidConfiguration(
					"Number of (local) data server should be 1");

		int serverPort = new Integer(addr[2]).intValue();

		CloudServer ds = new CloudServer(serverPort, 0);
		ds.init();

	}
}
